# -*- coding: utf-8 -*-

"""
处理celeA数据集
"""

import os
import threading
from PIL import Image
from PIL import ImageFile

ImageFile.LOAD_TRUNCATED_IMAGES = True
import parameter

'''多线程将图片缩放后再裁切到128*128分辨率'''
#裁切图片宽度
w = parameter.w
#裁切图片高度
h = parameter.h
#裁切点横坐标(以图片左上角为原点)
x = parameter.x
#裁切点纵坐标
y = parameter.y

#图片数据输入输出地址
inpath = parameter.inpath
outpath = parameter.outpath
#若输出不存在
if not os.path.exists(outpath):
    os.makedirs(outpath)


def cutArray(l, num):
  avg = len(l) / float(num)
  o = []
  last = 0.0

  while last < len(l):
    o.append(l[int(last):int(last + avg)])
    last += avg

  return o
  
def convertjpg(jpgfile,outdir,width=w,height=h):
    img=Image.open(jpgfile)
    (l,h) = img.size
    rate = min(l,h) / width
    try:
        img = img.resize((int(l // rate),int(h // rate)),Image.BILINEAR)
        img = img.crop((x,y,width+x,height+y))
        img.save(os.path.join(outdir,os.path.basename(jpgfile)))
    except Exception as e:
        print(e)

class thread(threading.Thread):
    def __init__(self, threadID, inpath, outpath, files):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.inpath = inpath
        self.outpath = outpath
        self.files = files
    def run(self):
        count = 0
        try:
            for file in self.files:
                convertjpg(self.inpath + file,self.outpath)
                count = count + 1
        except Exception as e:
            print(e)
        print('已处理图片数量：' +  str(count))
       

if __name__ == '__main__':
    if not os.path.exists(outpath):
        os.mkdir(outpath)
    files =  os.listdir(inpath)
    files = cutArray(files,8)
    threads = []
    for i in range(8):
        threads.append(thread(i+1, inpath, outpath, files[i]))
    
    for i in range(8):
        threads[i].start()
    
    for i in range(8):
        threads[i].join()
        
